<template>
  <MainLayout>
    <view class="page">
      <!-- 顶部导航栏 -->
      <view class="header">
        <text class="header-title">发布新帖</text>
        <button class="publish-btn" @click="handlePublish">发布</button>
      </view>

      <!-- 发帖表单 -->
      <view class="publish-form">
        <!-- 标题输入 -->
        <input 
          class="title-input" 
          v-model="postData.title" 
          placeholder="请输入帖子标题..." 
          maxlength="50"
        />

        <!-- 内容输入 -->
        <textarea 
          class="content-input" 
          v-model="postData.content" 
          placeholder="请输入帖子内容..." 
          maxlength="1000"
        />

        <!-- 图片上传区域 -->
        <view class="image-upload-section">
          <text class="section-title">添加图片</text>
          <view class="image-preview-container">
            <view 
              v-for="(image, index) in imageList" 
              :key="index" 
              class="image-preview-item"
            >
              <image :src="image" class="preview-image" mode="aspectFill" />
              <image 
                class="delete-icon" 
                src="/static/icons/delect/delete.svg" 
                @click="removeImage(index)"
              />
            </view>
            <view 
              class="upload-button" 
              v-if="imageList.length < 9" 
              @click="chooseImage"
            >
              <image class="upload-icon" src="/static/icons/addPicture.svg" />
              <text class="upload-text">{{ imageList.length }}/9</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </MainLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import MainLayout from '../../layout/MainLayout.vue'
import postApi from '../../http/models/post'
import imageApi from '../../http/models/image'

const postData = reactive({
  title: '',
  content: ''
})

const imageList = ref([]) // 本地图片路径列表
const uploadedImageUrls = ref([]) // 已上传的图片URL列表

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - imageList.value.length, // 最多选择9张
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: (res) => {
      imageList.value = [...imageList.value, ...res.tempFilePaths]
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 移除图片
const removeImage = (index) => {
  imageList.value.splice(index, 1)
}

// 上传图片
const uploadImages = async () => {
  const urls = []
  for (let i = 0; i < imageList.value.length; i++) {
    try {
      const res = await imageApi.uploadImage(imageList.value[i], 0) // 0表示帖子类型
      if (res.code === 200) {
        urls.push(res.data.imageUrl)
      } else {
        throw new Error(res.msg || '上传失败')
      }
    } catch (error) {
      console.error('上传图片失败:', error)
      uni.showToast({
        title: `图片上传失败: ${error.message}`,
        icon: 'none'
      })
      throw error
    }
  }
  return urls
}

// 发布帖子
const handlePublish = async () => {
  if (!postData.title.trim()) {
    uni.showToast({
      title: '请输入帖子标题',
      icon: 'none'
    })
    return
  }

  try {
    // 先上传图片
    if (imageList.value.length > 0) {
      uploadedImageUrls.value = await uploadImages()
    }

    // 发布帖子
    const params = {
      title: postData.title,
      content: postData.content,
      imageUrls: uploadedImageUrls.value
    }

    const res = await postApi.publishPost(params)
    if (res.code === 200) {
      uni.showToast({
        title: '发布成功',
        icon: 'success'
      })

      // 返回上一页并刷新
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1000)
    } else {
      uni.showToast({
        title: res.msg || '发布失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发布帖子失败:', error)
    uni.showToast({
      title: '发布失败，请重试',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0;
  margin: 0;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 999;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.publish-btn {
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
}

.publish-form {
  padding: 20px;
  background-color: #fff;
  margin-top: 10px;
}

.title-input {
  width: 100%;
  padding: 15px;
  font-size: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 20px;
  box-sizing: border-box;
}

.content-input {
  width: 100%;
  height: 200px;
  padding: 15px;
  font-size: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  box-sizing: border-box;
  margin-bottom: 20px;
  resize: none;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  display: block;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-preview-item {
  position: relative;
  width: 100px;
  height: 100px;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.delete-icon {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  background-color: white;
  border-radius: 50%;
}

.upload-button {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-icon {
  width: 30px;
  height: 30px;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
  color: #999;
}
</style>